package com.lh.jsp.pagetaglib;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;


public class PagerFilter implements Filter {
	
    public PagerFilter() {      
    }

	
	public void destroy() {
	
	}

	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		HttpServletRequest httpRequest = (HttpServletRequest)request;
		   //设置分页参数
		 SystemContext.setPagesize(getPagesize(httpRequest));
		  SystemContext.setOffset(getOffset(httpRequest));
		  
		  
		   try{
		    chain.doFilter(request, response);
		   }finally{
		    SystemContext.removeOffset();
		    SystemContext.removePagesize();
		   }  
	}

	
	
	
	private int getOffset(HttpServletRequest httpRequest){
		   int offset = 0;
		   try {
		    offset = Integer.parseInt(httpRequest.getParameter("pager.offset"));//得到标签自己计算出的pager.offset
		    int page = getPagesize(httpRequest);
		    if(0!=page){
		    	return page*15;
		    }
		   } catch (Exception ignore) {
		   }
		   return offset;
		} 
	//获取每页显示的行数
	private int getPagesize(HttpServletRequest httpRequest){
		
		String pageSize = httpRequest.getParameter("targetPage");// 得到用户自己的每页显示的行数

		if (pageSize != null) {
			Integer ps = null;
			try {
				ps = Integer.parseInt(pageSize);
				httpRequest.getSession().setAttribute("targetPage", ps.intValue());
			} catch (Exception ignore) {

			}
			return ps.intValue();
		}else{
			return 0;
		}
		
	   
	   
	}


	@Override
	public void init(FilterConfig arg0) throws ServletException {
		
		
	}
}
